axios.defaults.baseURL="http://localhost:8080";//配置基础路径
Vue.prototype.$http=axios;//配置全局属性

//1.axios前置拦截器：每次通过axios发送请求之前，让所有的请求都携带token
axios.interceptors.request.use(config => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        config.headers['token'] = token;
    }
    return config;
}, error => {
    Promise.reject(error);
})

//2.axios后置拦截器：后端处理完axios请求之后，处理响应的数据
axios.interceptors.response.use(res => {
    if (res.data.success === false && res.data.msg === "noLogin"){
        //删除localStorage的token和logininfo
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转到登录页面
        location.href="/login.html";
    }else if (false === res.data.success && "timeout" === res.data.msg) {
        alert("登录超时，请重新登录");
        //删除localStorage的token和logininfo
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转到登录页面
        location.href="login.html";
    }
    return res;
}, error => {
    Promise.reject(error);
})

//3.资源拦截
var url = location.href;
if(url.indexOf("login.html")==-1 && url.indexOf("register.html")==-1
    && url.indexOf("/callback.html")==-1 && url.indexOf("/binder.html")==-1){
    var logininfo = localStorage.getItem("logininfo");
    if(!logininfo){
        location.href="/login.html";
    }
}

//封装公用方法 - 将字符串的参数解析为json对象
function parseUrlParams2Obj(url) {//xxx?code=xxx&state=1
    let paramStr = url.substring(url.indexOf("?")+1);//code=xxx&state=1
    let paramArr = paramStr.split("&");//[code=xxx,state=1]
    let paramObj = {};
    for(let i = 0;i<paramArr.length;i++){
        let paramTemp = paramArr[i];//code=xxx
        let paramName = paramTemp.split("=")[0];//code
        let paramValue= paramTemp.split("=")[1];//xxx
        paramObj[paramName] = paramValue;//{code:xxx,state:1}
    }
    return paramObj;
}
